<?php

namespace app\admin\controller\warehouse;

use app\admin\model\Item;
use app\common\controller\Backend;
use app\admin\model\InventoryItemInfo;
use app\admin\model\out\OutInventoryAddr;
use think\Db;
use think\Exception;

/**
 * 出库记录管理
 */
class Outinventory extends Backend
{

    protected $model = null;
    protected $dataLimit = 'personal';
    protected $dataLimitField = 'uid';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\out\Inventory;

    }

    public function index()
    {
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $list = collection($list)->toArray();
            $wms = $this->getWarehouse();
            foreach ($list as $key => $value){
                foreach ($wms as $val){
                    if($value['warehouseid'] == $val['code']){
                        $list[$key]['warehouseid'] = $val['name'];
                    }
                }
                $items = current($this->getOutItems($value['id']));
                $list[$key]['items'] = $items['itemname'].' - '.$items['itemsku'].'  *  '.$items['instoragecount'];
            }
            $result = array("total" => $total, "rows" => $list,"wms"=>$wms);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * @return array|false|\PDOStatement|string|\think\Collection
     */
    public function getWarehouse(){

        $wmsModel = model('Warehouse');
        $wms = $wmsModel->select();
        $wms = collection($wms)->toArray();

        return $wms;
    }

    public function items(){
        $id = $this->request->post('id');

        if (!empty($id)) {
            $items = $this->getOutItems($id,'total');
            $this->success("请求成功", null, $items);
        }else{
            $this->success("网络异常，稍后重试！", null);
        }
    }

    /**
     * @param $outInventoryId
     * @return array|false|\PDOStatement|string|\think\Collection
     */
    public function getOutItems($outInventoryId,$type='single'){

        $itemInfo = model('InventoryItemInfo');
        if($type == 'single'){
            $rs = $itemInfo->where("inid","eq",$outInventoryId)->where("type","eq",2)->limit(0,1)->select();
        }else{
            $rs = $itemInfo->where("inid","eq",$outInventoryId)->where("type","eq",2)->select();
//            $item = collection($rs)->toArray();
//            $itemModel = model('Item');
//            foreach ($rs as $val){
//                if(empty($rs['itemname'])){
//                    $item = $itemModel->where('sku','eq',$rs['itemsku'])->getData();
//                    $rs['itemname'] = $item['itemname'];
//                }
//            }
        }


        return $rs;
    }

    /**
     * 导入出库
     */
    public function import()
    {
        $file = $this->request->request('file');
        if (!$file) {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        $filePath = ROOT_PATH . DS . 'public' . DS . $file;
        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }
        $PHPReader = new \PHPExcel_Reader_Excel2007();
        if (!$PHPReader->canRead($filePath)) {
            $PHPReader = new \PHPExcel_Reader_Excel5();
            if (!$PHPReader->canRead($filePath)) {
                $PHPReader = new \PHPExcel_Reader_CSV();
                if (!$PHPReader->canRead($filePath)) {
                    $this->error(__('Unknown data format'));
                }
            }
        }
        $PHPExcel = $PHPReader->load($filePath);
        $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
        $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
        $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
        $maxColumnNumber = \PHPExcel_Cell::columnIndexFromString($allColumn);

        $outInventory = new \app\admin\model\out\Inventory;
        try{
            for ($currentRow = 3; $currentRow <= $allRow; $currentRow++) {

                for ($currentColumn = 0; $currentColumn < 12; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $outAndAddr[] = is_null($val) ? '' : $val;
                }
                //保存出库记录
                Db::startTrans();
                $inData['warehouseid'] = 1;
                $inData['remark'] = $outAndAddr[1];
                $inData['orderid'] = $outAndAddr[2];
                $inOrderId = 'OUT' . date('Ymd') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
                $inData['outorderid'] = $inOrderId;
                $inData[$this->dataLimitField] = $this->auth->aid;

                $outInventory->save($inData);
                $outid = $outInventory->getLastInsID();
                //保存出库发货地址
                $address['recipients'] = $outAndAddr[3];
                $address['mobile'] = $outAndAddr[4];
                $address['company'] = $outAndAddr[5];
                //TODO 国家简称需要验证
                $address['state'] = $outAndAddr[6];
                $address['province'] = $outAndAddr[7];
                $address['city'] = $outAndAddr[8];
                $address['postcode'] = $outAndAddr[9];
                $address['addressone'] = $outAndAddr[10];
                $address['addresstwo'] = $outAndAddr[11];
                $address['outid'] = $outid;
                $address['outorderid'] = $inOrderId;
                $outInventoryAddr = new OutInventoryAddr;
                $outInventoryAddr->save($address);
                //保存出库关联商品
                for ($currentColumn = 12; $currentColumn < $maxColumnNumber; $currentColumn++) {
                    if ($currentColumn % 2 != 0) {
                        $sku = $currentSheet->getCellByColumnAndRow($currentColumn-1, $currentRow)->getValue();
                        $count = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();

                        $data['itemsku'] = $sku;
                        $data['instoragecount'] = $count;
                        $data['type'] = 2;
                        $data['inid'] = $outid;
                        $data['orderId'] = $inOrderId;
                        $data['warehouseid'] = 1;

                        if(!is_null($sku) && !empty($sku)){
                            $inItemInfo = new InventoryItemInfo;
                            $rsItem = $inItemInfo->save($data);
                            if ($rsItem === false) {
                                $this->error('导入失败，请检查格式');
                            }
                        }
                    }
                }
            }
            Db::commit();
            $this->success();
        } catch (\think\exception\PDOException $exception) {
            Db::rollback();
            $this->error($exception->getMessage());
        }

    }

}
